package com.ss.SmartStock.controller.user;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ss.SmartStock.common.*;
import com.ss.SmartStock.exception.BusinessException;
import com.ss.SmartStock.exception.ThrowUtils;
import com.ss.SmartStock.pojo.dto.product.*;
import com.ss.SmartStock.pojo.entity.*;
import com.ss.SmartStock.pojo.enums.StatusEnum;
import com.ss.SmartStock.pojo.vo.ProductQueryVO;
import com.ss.SmartStock.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author TsingFeng
 * @date 2024/6/17 17:10
 */
@Slf4j
@RestController("userProductController")
@Api(tags = "商品管理接口")
@RequestMapping("/user/product")
public class ProductController {
    @Resource
    private ProductDetailsService productDetailsService;

    @Resource
    private ProductService productService;
    @Resource
    private OperationService operationService;

    @Resource
    private UserService userService;
    @Resource
    private LogService logService;

    @Resource
    private PriceRecordsService priceRecordsService;

    /***
     * 添加商品
     */
    @PostMapping("/insertProduct")
    @ApiOperation(value = "添加商品")
    public BaseResponse<Boolean> insertProduct(@RequestBody ProductAddRequest productAddRequest) {

        Long adminid = BaseContext.getCurrentId();
        log.info("添加商品获取线程id:",BaseContext.getCurrentId());
        //创建日志，持久化

        productAddRequest.setOperator(adminid);
        ProductDetails productDetails = new ProductDetails();

        BeanUtils.copyProperties(productAddRequest, productDetails);

        int i= productDetailsService.insertProductDetails(productDetails);

        if(i==0) return ResultUtils.error(0,"插入失败！！");

        Long pDetailsId = productDetails.getPDetailsId();
        if(pDetailsId==null) return ResultUtils.error(0,"没有获取自增主键");

        //获取price_type自增主键
       PriceRecords priceRecords=new PriceRecords();

        BeanUtils.copyProperties(productAddRequest,priceRecords);

        BigDecimal cashPrice = priceRecords.getCashPrice();
        BigDecimal pointPrice = priceRecords.getPointPrice();
        if(cashPrice.compareTo(BigDecimal.ZERO)!=0 && pointPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("积分加钱");
        else if(cashPrice.compareTo(BigDecimal.ZERO)==0 && pointPrice.compareTo(BigDecimal.ZERO)==0) return ResultUtils.error(0,"积分数量和价格都为0");
        else if(cashPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("纯积分");
        else if(pointPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("现金购买");

        int i1 = priceRecordsService.insertPriceRecords(priceRecords);
        if(i1==0) return ResultUtils.error(0,"价格类型记录表插入失败");

        Long recordsId = priceRecords.getId();
        Product product=new Product();

        BeanUtils.copyProperties(productAddRequest,product);
        product.setProductDetailsId(pDetailsId);
        product.setProductPrice(recordsId);

        boolean p1 = productService.save(product);

        if (p1 ) {
            log.info("添加商品,用户id：", adminid);
            Log log = Log.builder().userId(adminid).logLevel("INFO").message("添加商品").build();
            logService.save(log);
            Operation operation = Operation.builder()
                    .pDetailsId(pDetailsId)
                    .status("新增")
                    .operationTime(LocalDateTime.now())
                    .remarks("新增商品")
                    .operatorId(BaseContext.getCurrentId())
                    .build();
            operationService.insertOperation(operation);

            return ResultUtils.success(p1);
        }else

        return ResultUtils.error(0, "新增商品信息失败");
    }

    /***
     * 修改商品信息
     */
    @GetMapping("/{id}")
    @ApiOperation("回显数据")
    public BaseResponse<Product> getById(@PathVariable Long id) {
        log.info("回显商品信息,商品id:{}", id);
        Log log = Log.builder().
                userId(BaseContext.getCurrentId()).
                logLevel("INFO").
                message("回显商品信息:"+id).build();
        logService.save(log);
        Product product = productService.getById(id);
        //todo 待优化
        return ResultUtils.success(product);
    }

    /**
     * 更新商品信息
     */
    @PostMapping("/update")
    @ApiOperation("修改商品信息")
    public BaseResponse<Boolean> updateProductMsg(@RequestBody ProductUpdateRequest ProductUpdateRequest){
        Long currentId = BaseContext.getCurrentId();
        log.info("修改商品信息，用户id：",currentId);
        Log log=Log.builder().userId(currentId).logLevel("INFO").message("修改商品信息").build();
        logService.save(log);
        Long productId = ProductUpdateRequest.getProductId();
        Product pro = productService.getById(productId);
        Long productDetailsId = pro.getProductDetailsId();
        Long productPrice = pro.getProductPrice();

        BeanUtils.copyProperties(ProductUpdateRequest,pro);

        boolean p1=productService.updateById(pro);

        //

        ProductDetails productDetails = productDetailsService.getById(productDetailsId);
        BeanUtils.copyProperties(ProductUpdateRequest,productDetails);
        boolean p2=productDetailsService.updateById(productDetails);

        //
        PriceRecords priceRecords=new PriceRecords();
        priceRecords.setId(productPrice);
        BeanUtils.copyProperties(ProductUpdateRequest,priceRecords);
        BigDecimal cashPrice = priceRecords.getCashPrice();
        BigDecimal pointPrice = priceRecords.getPointPrice();
        if(cashPrice.compareTo(BigDecimal.ZERO)!=0 && pointPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("积分加钱");
        else if(cashPrice.compareTo(BigDecimal.ZERO)==0 && pointPrice.compareTo(BigDecimal.ZERO)==0) return ResultUtils.error(0,"积分数量和价格都为0");
        else if(cashPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("纯积分");
        else if(pointPrice.compareTo(BigDecimal.ZERO)!=0) priceRecords.setName("现金购买");
        boolean p3 = priceRecordsService.updateById(priceRecords);

        if(p1 && p2 && p3)
        {
            return ResultUtils.success(p1);
        }

        return ResultUtils.error(0, "修改商品信息失败");
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    @ApiOperation("分页查询")
    public BaseResponse<Page<ProductQueryVO>> listProductVOByPage(ProductQueryRequest productQueryRequest, HttpServletRequest httpServletRequest) {

        if (productQueryRequest == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(httpServletRequest);

//        productQueryRequest.setUserName(loginUser.getUserName());

        long current = productQueryRequest.getCurrent();
        long size = productQueryRequest.getPageSize();

        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        Page<Product> productQueryRequestPage = productService.page(new Page<>(current, size),
                productService.getQueryWrapper(productQueryRequest));

        return ResultUtils.success(productService.getProductVOPage(productQueryRequestPage, httpServletRequest));
    }


    /***
     * 根据id队列删除商品
     */
    @GetMapping("/delete/idList")
    @ApiOperation("根据id队列删除商品")
    public BaseResponse<Boolean> deleteProductById(@RequestParam("idList") Collection<Long> idList, HttpServletRequest request) {
        if (idList == null || idList.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);

        List<Long> pdidList=new ArrayList<>();
        List<Long> prids=new ArrayList<>();
        for (Long id : idList) {
            Product product = productService.getById(id);
            ThrowUtils.throwIf(product == null, ErrorCode.NOT_FOUND_ERROR);
            //仅本人或管理员可删除
            if (!product.getOperator().equals(user.getId()) && !userService.isAdmin(user)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            Long productDetailsId = product.getProductDetailsId();
            Long productPrice = product.getProductPrice();
            pdidList.add(productDetailsId);
            prids.add(productPrice);
        }

        boolean flag = productService.removeByIds(idList);
        if(!flag) return ResultUtils.error(1,"删除商品基本信息失败");

        boolean flag2 = productDetailsService.removeByIds(pdidList);
        if(!flag2) return ResultUtils.error(2,"删除商品详情信息失败");

        boolean flag3 = priceRecordsService.removeByIds(prids);
        if(!flag2) return ResultUtils.error(3,"删除价格类型信息失败");


        return ResultUtils.success(flag);
    }

    /**
     * 查询商品
     *
     * @return
     */
    @GetMapping("/selectAll")
    @ApiOperation("查询商品")
    public BaseResponse<List<Product>> selectAll() {
        log.info("查询商品所有");
        Log log = Log.builder().
                userId(BaseContext.getCurrentId()).
                logLevel("INFO").
                message("查询所有商品").build();
        logService.save(log);

        return Result.success(productService.selectAllProduct());
    }

    /**
     * 发起审核申请
     */
    @PostMapping("/approval")
    @ApiOperation("小二发起审核")
    public BaseResponse<Boolean> approval(@RequestBody ProductApprovalRequest productApprovalRequest,
                                          HttpServletRequest request) {
        log.info("小二发起审核");
        Log log = Log.builder().
                userId(BaseContext.getCurrentId()).
                logLevel("INFO").
                message("小二发起审核").build();
        logService.save(log);

        Long pDetailsId = productApprovalRequest.getPDetailsId();

//        Product product = productService.getByDetailId(pDetailsId);
        //切换状态
//        product.setProductCheckState(StatusEnum.PENDING_REVIEW.getCode());

//        return ResultUtils.success(productService.updateById(product));
         return null;
    }
}
